package https

import (
	"io/ioutil"
	"net/http"
	"strings"
)

// 带cookie形式的获取网页
func Get(url string)(string,error){
	return GetHead(url, map[string]string{},true)
}

// 不带cookie形式的获取网页
func GetNoCookie(url string)(string,error){
	return GetHead(url, map[string]string{},false)
}

// 完整的获取网页信息，含请求头等
func GetHead(url string,head map[string]string,and_cookie bool)(string,error){
	client := &http.Client{}
	reqest, err := http.NewRequest("GET", url, nil) //建立一个请求
	if err != nil {
		return "",err
	}
	//添加固定请求头
	reqest.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
	reqest.Header.Set("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
	reqest.Header.Set("Connection", "keep-alive")
	reqest.Header.Add("Upgrade-Insecure-Requests","1")
	reqest.Header.Add("Host",GetDomainFromUrl(&url))
	reqest.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36")
	// 添加自定义请求头
	for i,v := range head{
		reqest.Header.Add(i,v)
	}
	if and_cookie {
		for _,v := range Cookies{
			reqest.Header.Add(v.Name,v.Value)
		}
	}
	response, err := client.Do(reqest) //提交
	if err != nil {
		return "",err
	}
	defer response.Body.Close()
	if and_cookie {
		Cookies = response.Cookies() //遍历cookies
	}
	body, err1 := ioutil.ReadAll(response.Body)
	if err1 != nil {
		return "",err
	}
	return string(body),nil
}

func PostNoCookie(url string,body string)(string,error){
	return PostHead(url, map[string]string{},false,body)
}
func Post(url string,body string)(string,error){
	return PostHead(url, map[string]string{},true,body)
}

// 完整的获取网页信息，含请求头等
func PostHead(url string,head map[string]string,and_cookie bool,form_body string)(string,error){
	client := &http.Client{}
	reqest, err := http.NewRequest("POST", url, strings.NewReader(form_body)) //建立一个请求
	if err != nil {
		return "",err
	}
	//添加固定请求头
	reqest.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	reqest.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
	reqest.Header.Set("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
	reqest.Header.Set("Connection", "keep-alive")
	reqest.Header.Add("Upgrade-Insecure-Requests","1")
	reqest.Header.Add("Host",GetDomainFromUrl(&url))
	reqest.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36")
	// 添加自定义请求头
	for i,v := range head{
		reqest.Header.Add(i,v)
	}
	if and_cookie {
		for _,v := range Cookies{
			reqest.Header.Add(v.Name,v.Value)
		}
	}
	response, err := client.Do(reqest) //提交
	if err != nil {
		return "",err
	}
	defer response.Body.Close()
	if and_cookie {
		Cookies = response.Cookies() //遍历cookies
	}
	body, err1 := ioutil.ReadAll(response.Body)
	if err1 != nil {
		return "",err
	}
	return string(body),nil
}